package com.xiaoke.web.controller;

import com.xiaoke.entity.Admin;
import com.xiaoke.utils.AjaxMsg;
import com.xiaoke.utils.ValidUtil;
import com.xiaoke.web.config.shiro.PasswordHelper;
import com.xiaoke.web.service.AdminService;
import com.xiaoke.web.service.DictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private DictionaryService dictionaryService;
    @Autowired
    private PasswordHelper passwordHelper;

    @RequestMapping(value = "/list")
    public String list(Model model) {
        Map map = new HashMap<>();
        List list = adminService.findByParams(map);
        model.addAttribute("list", list);
        return "admin/list";
    }


    @RequestMapping(value = "/input")
    public String input(Model model, String id) {
        Admin admin = adminService.selectByPrimaryKey(id);
        model.addAttribute("entity", admin);
        return "admin/input";
    }

    @RequestMapping(value = "/save")
    @ResponseBody
    public AjaxMsg save(Admin admin) {
        if (ValidUtil.isEmpty(admin.getId())) {
            Map map = new HashMap();
            map.put("username", admin.getUsername());
            List<Admin> admins = adminService.findByParams(map);
            if (!ValidUtil.isEmpty(admins))
                return new AjaxMsg(AjaxMsg.FAILURE, "账号已存在！");
            passwordHelper.encryptPassword(admin);
            adminService.insert(admin);
        } else {
            adminService.update(admin);
        }
        return new AjaxMsg();
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    public AjaxMsg delete(String id) {
        adminService.delete(id);
        return new AjaxMsg();
    }
}
